package com.market.controller;

import com.market.Dto.EmployeeLoginDto;
import com.market.Dto.EmployeeQueryDto;
import com.market.Dto.EmployeeSaveDto;
import com.market.Vo.EmployeeLoginVo;
import com.market.Vo.EmployeeQueryVo;
import com.market.entity.Employee;
import com.market.entity.UserInfo;
import com.market.service.EmployeeService;
import com.market.utils.JwtProperties;
import com.market.utils.JwtUtils;
import com.market.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/auth/login")
    public Result<EmployeeLoginVo> login(@RequestBody EmployeeLoginDto employeeLoginDto){
        Employee employee=employeeService.login(employeeLoginDto);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("empId", employee.getId());
        String token = JwtUtils.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVo employeeLoginVo=new EmployeeLoginVo();
        UserInfo userInfo=new UserInfo();
        BeanUtils.copyProperties(employee,userInfo);
        employeeLoginVo.setToken(token);
        employeeLoginVo.setUserInfo(userInfo);
        return Result.success(employeeLoginVo);
    }

    @PostMapping("/auth/logout")
    public Result<String> logout() {
        return Result.success();
    }
    /**
     * 获取员工列表
     * @param employeeeQueryDto
     * @return
     */

    @GetMapping("/employee/list")
    public Result<EmployeeQueryVo> list(EmployeeQueryDto employeeeQueryDto){
        return Result.success(employeeService.list(employeeeQueryDto));
    }

    /**
     * 获取员工详情
     */
    @GetMapping("/employee/{id}")
    public Result<Employee> getById(@PathVariable Long id){
        return Result.success(employeeService.getById(id));
    }

    /**
     * 新增员工
     */
    @PostMapping("/employee/add")
    public Result<String> save(@RequestBody EmployeeSaveDto employeeSaveDto){
        employeeService.saveEmployee(employeeSaveDto);
        return Result.success();
    }

    /**
     * 删除员工
     * @param id
     * @return
     */
    @DeleteMapping("/employee/delete/{id}")
    public Result<String> delete(@PathVariable Long id){
        employeeService.deleteEmployee(id);
        return Result.success();
    }

    /**
     * 修改员工
     * @param employeeSaveDto
     * @return
     */
    @PutMapping("/employee/update")
    public Result<String> update(@RequestBody EmployeeSaveDto employeeSaveDto){
        employeeService.updateEmployee(employeeSaveDto);
        return Result.success();
    }

}
